package com.xxxx.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.server.AdminUtils;
import com.xxxx.server.config.security.component.JwtTokenUtil;
import com.xxxx.server.mapper.AdminMapper;
import com.xxxx.server.mapper.AdminRoleMapper;
import com.xxxx.server.mapper.RoleMapper;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.AdminRole;
import com.xxxx.server.pojo.RespBean;
import com.xxxx.server.pojo.Role;
import com.xxxx.server.service.IAdminService;
import lombok.AccessLevel;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author GongXl
 * @since 2023-08-28
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
	@Resource
	private AdminMapper adminMapper;
	@Autowired
	private UserDetailsService userDetailsService;
	@Autowired
	private PasswordEncoder passwordEncoder;
	@Autowired
	private JwtTokenUtil jwtTokenUtil;

	@Value("${jwt.tokenHead}")
	private String tokenHead;

	@Autowired
	private RoleMapper roleMapper;
	@Getter(AccessLevel.NONE)
	@Autowired
	private AdminRoleMapper adminRoleMapper;
	/**
	 * @return com.xxxx.server.pojo.RespBean
	 * @Author GongXL
	 * @Description 登录后返回token
	 * @Date 15:26 2023/8/29
	 * @Param [java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest]
	 **/
	@Override
	public RespBean login(String username, String password, String code, HttpServletRequest request) {
		String captcha = (String) request.getSession().getAttribute("captcha");
		if (StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)) {
			return RespBean.error("验证码输入错误，请重新输入！");
		}

		UserDetails userDetails = userDetailsService.loadUserByUsername(username);
		if (null == userDetails || !passwordEncoder.matches(password, userDetails.getPassword())) {
			return RespBean.error("用户名或密码不正确");

		}
		if (!userDetails.isEnabled()) {
			return RespBean.error("账号被禁用，请联系管理员!");
		}
		UsernamePasswordAuthenticationToken authentication =
				new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
		SecurityContextHolder.getContext().setAuthentication(authentication);

		String token = jwtTokenUtil.generateToken(userDetails);
		Map<String, String> tokenMap = new HashMap<>();
		tokenMap.put("token", token);
		tokenMap.put("tokenHead", tokenHead);
		return RespBean.success("登录成功", tokenMap);
	}

	/**
	 * 根据用户名获取用户
	 *
	 * @param username
	 * @return
	 */
	@Override
	public Admin getAdminByUserName(String username) {
		return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username).eq("enabled", true));
	}

	/**
	 * 根据用户id查询用户角色列表
	 *
	 * @param adminId
	 * @return
	 */
	@Override
	public List<Role> getRoles(Integer adminId) {
		return roleMapper.getRoles(adminId);
	}

	/**
	 * 获取所有操作员
	 * @param keywords
	 * @return
	 */
	@Override
	public List<Admin> getAllAdmins(String keywords) {
		return adminMapper.getAllAdmins(AdminUtils.getCurrentAdmin().getId(),keywords);
	}

	/**
	 * 更新操作员角色
	 * @param adminId
	 * @param rids
	 * @return
	 */
	@Override
	@Transactional
	public RespBean updateAdminRole(Integer adminId, Integer[] rids) {
		adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId",adminId));
		Integer result = adminRoleMapper.addAdminRole(adminId, rids);
		if(rids.length == result){
			return RespBean.success("更新成功");
		}
		return RespBean.error("更新失败");
	}

}
